package com.lamthun.common.util;

import java.util.*;

/**
 * 抛硬币算法
 *
 * @author lamthun
 */
public class TossCoin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入硬币的数量: ");
        int coinNumber = sc.nextInt();

        List<String> binaryList = new ArrayList<>();
        for (int i = 0; i < bToD(coinNumber); i++) {
            binaryList.add(toFullBinaryString(i, coinNumber));
        }

        Map<Integer, List<String>> countMap = new LinkedHashMap<>();
        for (int i = 0; i <= coinNumber; i++) {
            countMap.put(i, countAndPut(i, binaryList));
        }

        for (Map.Entry<Integer, List<String>> entry : countMap.entrySet()) {
            System.out.println("结果等于[" + entry.getKey() + "]的排列组合占比是: " + entry.getValue().size() + "/" + binaryList.size());
//            System.out.println("结果等于[" + entry.getKey() + "]的排列组合详细列表如下: "  + entry.getValue());
//            System.out.println();
        }
    }

    private static int bToD(int power) {
        String twoPower = "";
        for (int i = 0; i < power; i++) {
            twoPower += "1";
        }
        return Integer.parseInt(twoPower, 2) + 1;
    }

    private static List<String> countAndPut(int num, List<String> binaryList) {
        List<String> countList = new ArrayList<>();
        for (String binary : binaryList) {
            String[] ss = binary.split("");
            if (num == sum(ss)) {
                countList.add(binary);
            }
        }
        return countList;
    }

    private static int sum(String[] ss) {
        int sum = 0;
        for (String numS : ss) {
            sum += Integer.parseInt(numS);
        }
        return sum;
    }

    private static String toFullBinaryString(int num, int length) {
        char[] chs = new char[Integer.SIZE];
        for (int i = 0; i < Integer.SIZE; i++) {
            chs[Integer.SIZE - 1 - i] = (char) (((num >> i) & 1) + '0');
        }
        return new String(chs).substring(32 - length, 32);
    }
}
